import { useState, useEffect, useCallback } from "react";
import { View, ScrollView } from "@tarojs/components";
import { getReportRead } from "@/axios/report";
import { colChartStat } from "@/axios/english";
import { IHeaderBox, IBarCharts } from "@/components/index";

import "./index.scss";

interface ELPIndexProps {}

const typeMap: API.OptionItem[] = [
  { label: "人数", value: 1 },
  { label: "平均分", value: 2 },
];

const ELPIndex: React.FC<ELPIndexProps> = () => {
  const [triggered, setTriggered] = useState<boolean>(false);
  const [feedBack, setFeedBack] = useState<string>("");

  const [type, setType] = useState<number>(1);
  const [chartData, setChartData] = useState<API.ChartStatItem[]>([]);
  const handleChangeType = (value: number) => {
    setType(value);
  };

  const getChartData = useCallback(async () => {
    try {
      const results = await colChartStat({ tab: type });
      setChartData(results);
      setTriggered(false);
    } catch {}
  }, [type]);

  const init = async () => {
    try {
      const results = await getReportRead({ subjectId: 5 });
      setFeedBack(results);
    } catch {}
  };

  useEffect(() => {
    init();
  }, []);

  useEffect(() => {
    getChartData();
  }, [getChartData]);

  const onRefresh = () => {
    init();
    getChartData();
    setTriggered(true);
  };

  return (
    <ScrollView
      scrollY
      className="scrollview"
      onRefresherRefresh={onRefresh}
      enableBackToTop
      refresherEnabled
      refresherTriggered={triggered}
      scrollWithAnimation
    >
      <View className="common_page">
        <View className="card_box chart_box">
          <IHeaderBox
            title="英语能力"
            options={typeMap}
            current={type}
            handleClick={handleChangeType}
          />
          <IBarCharts id="elp_chart" data={chartData} />
        </View>
        <View className="card_box data_box">
          <IHeaderBox title="反馈建议" />
          <View className="data_info">
            <View
              className="feedBack"
              dangerouslySetInnerHTML={{ __html: feedBack }}
            ></View>
          </View>
        </View>
      </View>
    </ScrollView>
  );
};

export default ELPIndex;
